package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/26 19:54
 */
public class C29 {


    public static int divide(int dividend, int divisor) {
        if (divisor == 1 || divisor == -1) {
            return dividend == Integer.MIN_VALUE && divisor == -1 ? Integer.MAX_VALUE : dividend * divisor;
        }
        return dividend / divisor;
    }

    public static int divide2(int dividend, int divisor) {
        if (divisor == 1 || divisor == -1) {
            return dividend == Integer.MIN_VALUE && divisor == -1 ? Integer.MAX_VALUE : dividend * divisor;
        }
        long ans = process(Math.abs((long) dividend), Math.abs((long)divisor));
        return (int) (((dividend^divisor) >> 31 & 1) == 1 ? -ans : ans);
    }

    public static long process(long dividend, long divisor) {
        if (dividend < divisor) return 0;
        long ans = 1;
        long step = divisor << 1;
        while (dividend > step) {
            step <<= 1;
            ans <<= 1;
        }
        return ans + process(dividend - (step >> 1), divisor);
    }


    public static void main(String[] args) {
        long a = (long) Integer.MAX_VALUE + 1;
        System.out.println(a);
        System.out.println((int)a);
        int num1 = Integer.MIN_VALUE;
        int num2 = -1;
        System.out.println(divide(num1, num2));
        System.out.println(divide2(num1, num2));
    }

}
